package com.hisan.freeride.home.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;

import com.bumptech.glide.Glide;
import com.codbking.widget.DatePickDialog;
import com.codbking.widget.bean.DateType;
import com.hisan.freeride.R;
import com.hisan.freeride.common.base.AppConfig;
import com.hisan.freeride.common.base.BaseActivity;
import com.hisan.freeride.common.callback.DialogCallback;
import com.hisan.freeride.common.utils.CacheUtils;
import com.hisan.freeride.common.utils.CollectionUtils;
import com.hisan.freeride.common.utils.GlideImageLoader;
import com.hisan.freeride.common.utils.GsonUtils;
import com.hisan.freeride.common.utils.ImageUtils;
import com.hisan.freeride.databinding.DataBinding;
import com.hisan.freeride.home.model.ImageUrl;
import com.hisan.freeride.home.model.MyImageUrl;
import com.hisan.freeride.home.model.UserData;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.view.CropImageView;
import com.lzy.okgo.OkGo;
import com.mylhyl.circledialog.CircleDialog;
import com.mylhyl.circledialog.callback.ConfigButton;
import com.mylhyl.circledialog.callback.ConfigDialog;
import com.mylhyl.circledialog.params.ButtonParams;
import com.mylhyl.circledialog.params.DialogParams;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

;


/**
 * 创建时间 : 2017/6/6
 * 创建人：yangyingqi
 * 公司：嘉善和盛网络有限公司
 * 备注：个人中心
 */
public class DataActivity extends BaseActivity<DataBinding> {
    //图片集合
    private ArrayList<ImageItem> imageItems;
    //头像地址
    private String avatar="";
    private Intent intent;

    @Override
    protected int getLayoutId() {
        return R.layout.data;
    }

    //初始化布局
    @Override
    protected void initView() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoader());
        imagePicker.setMultiMode(false);//设置选择图片圆形剪切
        imagePicker.setShowCamera(true);                      //显示拍照按钮
        imagePicker.setCrop(true);                           //允许裁剪（单选才有效）
        imagePicker.setSelectLimit(1);              //选中数量限制
        imagePicker.setStyle(CropImageView.Style.CIRCLE);  //裁剪框的形状
        imagePicker.setOutPutX(120);                         //保存文件的宽度。单位像素
        imagePicker.setOutPutY(120);                         //保存文件的高度。单位像素
    }

    @Override
    protected void initEvent() {
        mBinding.topBack.setOnClickListener(v -> finishActivity(true));
        mBinding.selectAvatar.setOnClickListener(v -> toImage());
        mBinding.selectName.setOnClickListener(v -> {
            Bundle bundle=new Bundle();
            bundle.putString("name","修改昵称");
            startActivityForResult(NickNameActivity.class,97,bundle,true);
        });
        mBinding.selectSex.setOnClickListener(v -> {
            final String[] items = {"男", "女", "保密"};
            new CircleDialog.Builder(DataActivity.this)
                    .configDialog(new ConfigDialog() {
                        @Override
                        public void onConfig(DialogParams params) {
                        }
                    })
                    .setTitle("选择性别")
                    .setTitleColor(getResources().getColor(R.color.home_titel))
                    .setItems(items, (parent, view, position, id) -> mBinding.sexName.setText(items[position]))
                    .setNegative("取消", null)
                    .configNegative(new ConfigButton() {
                        @Override
                        public void onConfig(ButtonParams params) {
                            //取消按钮字体颜色
                            params.textColor = getResources().getColor(R.color.home_titel);
                        }
                    })
                    .show();
        });
        //填写行业名称
        mBinding.selectIndustry.setOnClickListener(v -> {
            Bundle bundle=new Bundle();
            bundle.putString("name","修改行业");
            startActivityForResult(NickNameActivity.class,97,bundle,true);
        });
        //填写公司名称
        mBinding.selectCompany.setOnClickListener(v -> {
            Bundle bundle=new Bundle();
            bundle.putString("name","修改公司");
            startActivityForResult(NickNameActivity.class,97,bundle,true);
        });
        //填写职业
        mBinding.selectCareer.setOnClickListener(v -> {
            Bundle bundle=new Bundle();
            bundle.putString("name","修改职业");
            startActivityForResult(NickNameActivity.class,97,bundle,true);
        });
        //填写个性签名
        mBinding.selectSign.setOnClickListener(v -> startActivityForResult(SignatureActivity.class,98,null,true));
        mBinding.selectYear.setOnClickListener(v -> showDatePickDialog(DateType.TYPE_YMD));
        mBinding.editOk.setOnClickListener(v -> upuser());
        mBinding.selectOwner.setOnClickListener(v -> {
            if (mBinding.ownerName.getText().toString().equals("未认证")){
                startActivityForResult(CartCertificationActivity.class,99,null,true);
            }
        });
        mBinding.selectReal.setOnClickListener(v -> {
            if (mBinding.realName.getText().toString().equals("未认证")){
                startActivityForResult(RealNameActivity.class,99,null,true);
            }
        });
    }

    @Override
    protected void loadData(boolean isRefresh) {
        OkGo.<UserData>get(AppConfig.ReadUrl)
                .tag(this)
                .execute(new DialogCallback<UserData>(this) {
                    @Override
                    public void onSuccess(com.lzy.okgo.model.Response<UserData> response) {
                        super.onSuccess(response);
                        if (!CollectionUtils.isNullOrEmpty(response.body())){
                            if (!CollectionUtils.isNullOrEmpty(response.body())){
                                if (!CollectionUtils.isNullOrEmpty(response.body().getAvatar())){
                                    Uri uri=Uri.parse(response.body().getAvatar());
                                    Glide.with(getApplication())
                                            .load(uri)
                                            .placeholder(R.mipmap.avator)//设置占位图
                                            .error(R.mipmap.avator)
                                            .into(mBinding.pAvatar);
                                }
                                mBinding.uName.setText(response.body().getNickname());
                                mBinding.sexName.setText(response.body().getSex());
                                mBinding.yearName.setText(response.body().getBirthday()+"");
                                mBinding.industryName.setText(response.body().getWork_industry());
                                mBinding.companyName.setText(response.body().getWork_company());
                                mBinding.careerName.setText(response.body().getWork_occupation());
                                mBinding.sign.setText(response.body().getSignature());
                                avatar=response.body().getAvatar();
                                mBinding.exp.setText(response.body().getWallet().getExperience()+"分");
                            }
                            if (response.body().getIs_realname()==0){
                                mBinding.realName.setText("未认证");
                                mBinding.realIamge.setImageResource(R.mipmap.radio);
                            }else{
                                mBinding.realName.setText("已认证");
                                mBinding.realIamge.setImageResource(R.mipmap.radio_fill);
                            }
                            if (response.body().getIs_driver()==0){
                                mBinding.ownerName.setText("未认证");
                                mBinding.ownerIamge.setImageResource(R.mipmap.radio);
                            }else{
                                mBinding.ownerName.setText("已认证");
                                mBinding.ownerIamge.setImageResource(R.mipmap.radio_fill);
                            }
                        }
                    }
                });
    }

    private void toImage() {
        final String[] items = {"相册", "相机"};
        new CircleDialog.Builder(this)
                .configDialog(new ConfigDialog() {
                    @Override
                    public void onConfig(DialogParams params) {
                    }
                })
                .setTitle("选择照片")
                .setTitleColor(getResources().getColor(R.color.home_titel))
                .setItems(items, (parent, view, position, id) -> {
                    if (!CollectionUtils.isNullOrEmpty(items)){
                        if (items[position].equals("相册")){
                            Intent intent1 = new Intent(DataActivity.this,ImageGridActivity.class);
                            startActivityForResult(intent1, 100);
                        }else{
                            Intent intent1 = new Intent(DataActivity.this, ImageGridActivity.class);
                            intent1.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS,true); // 是否是直接打开相机
                            startActivityForResult(intent1, 100);
                        }
                    }
                })
                .setNegative("取消", null)
                .configNegative(new ConfigButton() {
                    @Override
                    public void onConfig(ButtonParams params) {
                        //取消按钮字体颜色
                        params.textColor = getResources().getColor(R.color.home_titel);
                    }
                })
                .show();
    }

    //选择日期
    private void showDatePickDialog(DateType type) {
        DatePickDialog dialog = new DatePickDialog(this);
        //设置上下年分限制
        dialog.setYearLimt(100);
        //设置标题
        dialog.setTitle("选择时间");
        //设置类型
        dialog.setType(type);
        //设置消息体的显示格式，日期格式
        dialog.setMessageFormat("yyyy-MM-dd");
        //设置选择回调
        dialog.setOnChangeLisener(null);
        //设置点击确定按钮回调
        dialog.setOnSureLisener(date -> {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String s = sdf.format(date);
            mBinding.yearName.setText(s);

        });
        dialog.show();
    }

    //更新用户数据
    private void upuser() {
        String nickname=mBinding.uName.getText().toString();
        String sex= mBinding.sexName.getText().toString();
        String birthday= mBinding.yearName.getText().toString();
        String work_industry= mBinding.industryName.getText().toString();
        String work_company= mBinding.companyName.getText().toString();
        String work_occupation= mBinding.careerName.getText().toString();
        String signature=mBinding.sign.getText().toString();
        OkGo.put(AppConfig.SaveuserInfo)
                .tag(this)
                .params("nickname",nickname)
                .params("avatar",avatar)
                .params("work_industry",work_industry)
                .params("work_company",work_company)
                .params("work_occupation",work_occupation)
                .params("work_occupation",work_occupation)
                .params("sex",sex)
                .params("birthday",birthday)
                .params("signature",signature)
                .execute(new DialogCallback<Object>(this) {
                    @Override
                    public void onSuccess(com.lzy.okgo.model.Response<Object> response) {
                        super.onSuccess(response);
                        if (isOk(response)){
                            showToast("数据更新成功");
                            if (CollectionUtils.isNullOrEmpty(intent)){
                                intent=new Intent();
                            }
                            setResult(97,intent);
                            finishActivity(true);
                        }else {
                            showError(response);
                        }
                    }

                    @Override
                    public void onError(com.lzy.okgo.model.Response<Object> response) {
                        super.onError(response);
                        showError(response);
                    }
                });
    }





    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (!CollectionUtils.isNullOrEmpty(data) && requestCode == 100) {
            if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
                imageItems = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (imageItems != null && imageItems.size() > 0) {
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < imageItems.size(); i++) {
                        if (i == imageItems.size() - 1)
                            sb.append("图片").append(i + 1).append(" ： ").append(imageItems.get(i).path);
                        else
                            sb.append("图片").append(i + 1).append(" ： ").append(imageItems.get(i).path).append("\n");
                    }
                    formUpload();
                } else {
                    showToast("没有选择图片");
                }
            }
        }else if (resultCode==99){
            loadData(true);
        }else if (resultCode==98){
            if (!CollectionUtils.isNullOrEmpty(data)){
                mBinding.sign.setText(data.getStringExtra("name"));}
        }else if (resultCode==97){
            if (!CollectionUtils.isNullOrEmpty(data)){
                String type=data.getStringExtra("type");
                if (type.equals("修改昵称")){
                    mBinding.uName.setText(data.getStringExtra("name"));
                }else  if (type.equals("修改行业")){
                    mBinding.industryName.setText(data.getStringExtra("name"));
                }else  if (type.equals("修改公司")){
                    mBinding.companyName.setText(data.getStringExtra("name"));
                }else  if (type.equals("修改职业")){
                    mBinding.careerName.setText(data.getStringExtra("name"));
                }
            }
        }
    }

    //上传图片
    private  void formUpload(){
        ArrayList<File> files = new ArrayList<>();
        if (imageItems != null && imageItems.size() > 0) {
            for (int i = 0; i < imageItems.size(); i++) {
                files.add(new File(imageItems.get(i).path));
            }
            for (File file:files){
                Bitmap bitmap= ImageUtils.getBitmap(file);
                ImageUtils.compressBitmapToFile(bitmap,file);
            }
        }
        OkGo.post(AppConfig.UpLoad)
                .tag(this)
                .addFileParams("image", files)
                .execute(new DialogCallback<Object>(DataActivity.this){
                    @Override
                    public void onSuccess(com.lzy.okgo.model.Response<Object> response) {
                        super.onSuccess(response);
                        if (!CollectionUtils.isNullOrEmpty(response)) {
                            if (isOk(response)){
                               String data= GsonUtils.GsonString(response.body());
                                MyImageUrl imageUrl=GsonUtils.GsonToBean(data, MyImageUrl.class);
                                avatar = imageUrl.getFile();
//                                try {
//                                    JSONObject json = new JSONObject(response.body().toString());

                                    CacheUtils.getInstance().put("avatar",avatar);
                                    if (!CollectionUtils.isNullOrEmpty(avatar)) {
                                        Uri uri=Uri.parse(avatar);
                                        Glide.with(getApplication())
                                                .load(uri)
                                                .placeholder(R.mipmap.avator)//设置占位图
                                                .error(R.mipmap.avator)
                                                .into(mBinding.pAvatar);
                                    }
//                                } catch (JSONException e) {
//                                    e.printStackTrace();}
                        }
                        }else {
                            showError(response);
                        }
                    }

                    @Override
                    public void onError(com.lzy.okgo.model.Response<Object> response) {
                        super.onError(response);
                        showError(response);
                    }
                });

    }
}
